<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>活动列表 - 校园活动报名平台</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link href="css/styles.css" rel="stylesheet">
    <link href="css/custom-icons.css" rel="stylesheet">
    <style>
        /* 活动列表页特定样式 */
        .main-content {
            padding: 2rem 0;
        }
        
        .activities-header {
            margin-bottom: 2rem;
        }
        
        .activities-header h2 {
            font-weight: 700;
            color: var(--primary-color);
        }
        
        .activity-card {
            border-radius: 0.75rem;
            overflow: hidden;
            transition: all 0.3s;
            height: 100%;
        }
        
        .activity-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 0.5rem 1.5rem rgba(0, 0, 0, 0.15);
        }
        
        .activity-image {
            display: none;
        }
        
        .activity-date {
            position: absolute;
            top: 1rem;
            right: 1rem;
            background-color: rgba(var(--primary-color-rgb), 0.1);
            padding: 0.5rem;
            border-radius: 0.5rem;
            font-size: 0.8rem;
            font-weight: 600;
            color: var(--primary-color);
        }
        
        .activity-meta {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
            color: #6c757d;
            font-size: 0.85rem;
        }
        
        .activity-category {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 1rem;
            font-size: 0.75rem;
            font-weight: 600;
            background-color: #e8eaf6;
            color: var(--primary-color);
        }
        
        .activity-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #e9ecef;
        }
        
        .participants {
            font-size: 0.85rem;
            color: #6c757d;
        }
        
        .participants .full {
            color: var(--danger-color);
        }
        
        .activity-status {
            display: inline-block;
            width: 0.75rem;
            height: 0.75rem;
            border-radius: 50%;
            margin-right: 0.25rem;
        }
        
        .status-active {
            background-color: var(--secondary-color);
        }
        
        .status-soon {
            background-color: var(--warning-color);
        }
        
        .status-full {
            background-color: var(--danger-color);
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-white">
        <div class="container">
            <a class="navbar-brand" href="index.html">
                <i class="fas fa-calendar-check me-2"></i>校园活动
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link active" href="activities.html">
                            <i class="fas fa-list me-1"></i>活动列表
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="create-activity.html">
                            <i class="fas fa-plus-circle me-1"></i>创建活动
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="my-activities.html">
                            <i class="fas fa-bookmark me-1"></i>我的活动
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="profile.html">
                            <i class="fas fa-user me-1"></i>个人信息
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-user-circle me-1"></i><span id="currentUsername">用户</span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                            <li><a class="dropdown-item" href="profile.html"><i class="fas fa-id-card me-2"></i>个人资料</a></li>
                            <li><a class="dropdown-item" href="my-activities.html"><i class="fas fa-list-alt me-2"></i>我的活动</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" id="logoutBtn"><i class="fas fa-sign-out-alt me-2"></i>退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <header class="header">
        <div class="container">
            <div class="row">
                <div class="col-md-8 mx-auto text-center">
                    <h1>校园活动列表</h1>
                    <p class="lead">发现精彩校园活动，开启您的多彩大学生活</p>
                </div>
            </div>
        </div>
    </header>

    <div class="container main-content">
        <div class="row fade-in" id="activityList">
            <!-- 活动卡片将在这里动态加载 -->
        </div>
    </div>

    <!-- 活动详情模态框 -->
    <div class="modal fade" id="activityDetailModal" tabindex="-1" aria-labelledby="activityDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="activityDetailModalLabel">活动详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="activityDetailContent">
                    <!-- 活动详情内容将在这里动态加载 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="registerActivityBtn">
                        <i class="fas fa-user-plus me-2"></i>报名参加
                    </button>
                </div>
            </div>
        </div>
    </div>

    <footer class="footer text-center py-4">
        <div class="container">
            <p class="mb-0">© 2025 校园活动报名平台 | <i class="fas fa-code"></i> 用心打造</p>
        </div>
    </footer>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let currentUser = null;
        let currentActivity = null;
        let allActivities = [];
        const API_BASE_URL = '/api';

        // 标准化类别
        function standardizeCategory(rawCategory) {
            if (!rawCategory) {
                return { name: '其他活动', icon: 'fas fa-calendar-alt' };
            }
            
            // 确保是字符串类型
            const categoryStr = String(rawCategory);
            const categoryLower = categoryStr.toLowerCase();
            
            // 类别映射
            const categories = {
                '学术': { name: '学术讲座', icon: 'fas fa-book' },
                'academic': { name: '学术讲座', icon: 'fas fa-book' },
                '0': { name: '学术讲座', icon: 'fas fa-book' },
                
                '体育': { name: '体育赛事', icon: 'fas fa-basketball-ball' },
                'sports': { name: '体育赛事', icon: 'fas fa-basketball-ball' },
                '1': { name: '体育赛事', icon: 'fas fa-basketball-ball' },
                
                '文艺': { name: '文艺演出', icon: 'fas fa-music' },
                'entertainment': { name: '文艺演出', icon: 'fas fa-music' },
                '2': { name: '文艺演出', icon: 'fas fa-music' },
                
                '志愿': { name: '志愿公益', icon: 'fas fa-hands-helping' },
                'volunteer': { name: '志愿公益', icon: 'fas fa-hands-helping' },
                '3': { name: '志愿公益', icon: 'fas fa-hands-helping' },
                
                '社团': { name: '社团活动', icon: 'fas fa-users' },
                'club': { name: '社团活动', icon: 'fas fa-users' },
                '4': { name: '社团活动', icon: 'fas fa-users' },
                
                '其他': { name: '其他活动', icon: 'fas fa-calendar-alt' },
                'other': { name: '其他活动', icon: 'fas fa-calendar-alt' },
                '5': { name: '其他活动', icon: 'fas fa-calendar-alt' }
            };
            
            // 完整类别名称映射
            const fullCategories = {
                '学术讲座': { name: '学术讲座', icon: 'fas fa-book' },
                '体育赛事': { name: '体育赛事', icon: 'fas fa-basketball-ball' },
                '文艺演出': { name: '文艺演出', icon: 'fas fa-music' },
                '志愿公益': { name: '志愿公益', icon: 'fas fa-hands-helping' },
                '社团活动': { name: '社团活动', icon: 'fas fa-users' },
                '其他活动': { name: '其他活动', icon: 'fas fa-calendar-alt' }
            };
            
            // 先尝试完整匹配
            if (fullCategories[categoryStr]) {
                return fullCategories[categoryStr];
            }
            
            // 尝试精确匹配
            if (categories[categoryLower]) {
                return categories[categoryLower];
            }
            
            // 默认返回其他活动
            return { name: '其他活动', icon: 'fas fa-calendar-alt' };
        }

        // 页面加载完成后执行
        $(document).ready(function() {
            // 检查登录状态
            checkLoginStatus();

            // 初始化事件监听
            initEvents();
        });

        // 初始化事件监听
        function initEvents() {
            // 退出登录按钮点击事件
            $('#logoutBtn').on('click', function() {
                logout();
            });

            // 报名按钮点击事件
            $('#registerActivityBtn').on('click', function() {
                registerForActivity(currentActivity.id, currentUser.id);
            });
            
            // 使用事件委托绑定查看详情按钮点击事件
            $(document).on('click', '.view-detail-btn', function() {
                const activityId = $(this).data('id');
                viewActivityDetail(activityId);
            });
        }

        // 检查登录状态
        function checkLoginStatus() {
            const user = localStorage.getItem('currentUser');
            if (user) {
                currentUser = JSON.parse(user);
                $('#currentUsername').text(currentUser.name || currentUser.username);
                loadActivities();
            } else {
                // 未登录，跳转到登录页面
                window.location.href = 'login.html';
            }
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('currentUser');
            window.location.href = 'login.html';
        }

        // 加载活动列表
        function loadActivities() {
            // 显示加载中状态
            $('#activityList').html('<div class="col-12 text-center py-5"><i class="fas fa-spinner fa-spin fa-3x"></i><p class="mt-3">正在加载活动...</p></div>');
            
            $.ajax({
                url: API_BASE_URL + '/activities/active',
                type: 'GET',
                success: function(response) {
                    if (response.code === 200) {
                        allActivities = response.data;
                        console.log('加载的活动总数:', allActivities.length);
                        displayActivities(allActivities);
                    } else {
                        alert('获取活动列表失败：' + response.message);
                    }
                },
                error: function(xhr) {
                    alert('获取活动列表失败：' + (xhr.responseJSON?.message || '服务器错误'));
                }
            });
        }

        // 显示活动列表
        function displayActivities(activities) {
            const container = $('#activityList');
            container.empty();

            if (activities.length === 0) {
                container.html(`
                    <div id="no-activities-message" class="col-12 text-center py-5">
                        <i class="fas fa-calendar-times fa-3x text-muted"></i>
                        <p class="mt-3 text-muted">未找到相关活动</p>
                    </div>
                `);
                return;
            }

            activities.forEach(function(activity) {
                const startTime = new Date(activity.startTime);
                const endTime = new Date(activity.endTime);
                const deadline = new Date(activity.registrationDeadline);
                
                const isFull = activity.maxParticipants && activity.currentParticipants >= activity.maxParticipants;
                const isComingSoon = startTime > new Date();
                
                // 获取类别信息用于图标显示
                const categoryInfo = standardizeCategory(activity.categoryName);
                
                const card = `
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="card activity-card">
                            <div class="card-body">
                                <div class="activity-date">
                                    <i class="far fa-calendar-alt me-1"></i>${startTime.toLocaleDateString()}
                                </div>
                                <div class="activity-meta">
                                    <span class="activity-category">
                                        <i class="${categoryInfo.icon} me-1"></i>${categoryInfo.name}
                                    </span>
                                    <span class="activity-location">
                                        <i class="fas fa-map-marker-alt me-1"></i>${activity.location}
                                    </span>
                                </div>
                                <h5 class="card-title">${activity.title}</h5>
                                <p class="card-text text-muted">${activity.description.substring(0, 80)}${activity.description.length > 80 ? '...' : ''}</p>
                                
                                <div class="activity-footer">
                                    <div class="participants">
                                        <i class="fas fa-users me-1"></i>
                                        <span class="${isFull ? 'full' : ''}">${activity.currentParticipants}/${activity.maxParticipants || '不限'}</span>
                                    </div>
                                    <button class="btn btn-sm btn-outline-primary view-detail-btn" data-id="${activity.id}">
                                        查看详情
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                container.append(card);
            });
        }

        // 查看活动详情
        function viewActivityDetail(activityId) {
            console.log('查看活动详情，ID:', activityId);
            
            if (!activityId) {
                console.error('活动ID为空');
                alert('无法查看活动详情：活动ID为空');
                return;
            }
            
            $.ajax({
                url: API_BASE_URL + '/activities/' + activityId,
                type: 'GET',
                success: function(response) {
                    console.log('获取活动详情成功:', response);
                    if (response.code === 200) {
                        currentActivity = response.data;
                        displayActivityDetail(currentActivity);
                        
                        // 显示模态框
                        const modal = new bootstrap.Modal(document.getElementById('activityDetailModal'));
                        modal.show();
                    } else {
                        console.error('获取活动详情失败:', response.message);
                        alert('获取活动详情失败：' + response.message);
                    }
                },
                error: function(xhr) {
                    console.error('获取活动详情请求错误:', xhr);
                    alert('获取活动详情失败：' + (xhr.responseJSON?.message || '服务器错误'));
                }
            });
        }

        // 显示活动详情
        function displayActivityDetail(activity) {
            const startTime = new Date(activity.startTime).toLocaleString();
            const endTime = new Date(activity.endTime).toLocaleString();
            const deadline = new Date(activity.registrationDeadline).toLocaleString();
            
            // 检查是否已报名
            const alreadyRegistered = currentUser.id && 
                activity.participants && 
                activity.participants.some(user => user.id === currentUser.id);
            
            // 检查是否已满
            const isFull = activity.maxParticipants && 
                activity.currentParticipants >= activity.maxParticipants;
            
            const content = `
                <div class="card border-0">
                    <div class="card-body">
                        <h3 class="mb-3">${activity.title}</h3>
                        <div class="d-flex justify-content-between mb-3">
                            <span class="badge bg-primary"><i class="fas fa-user me-1"></i>${activity.creatorName}</span>
                            <span class="badge ${activity.isActive ? 'bg-success' : 'bg-danger'}">
                                <i class="fas fa-${activity.isActive ? 'check-circle' : 'times-circle'} me-1"></i>
                                ${activity.isActive ? '正在进行' : '已结束'}
                            </span>
                        </div>
                        
                        <div class="mb-4">
                            ${activity.description.split('\n').map(paragraph => `<p>${paragraph}</p>`).join('')}
                        </div>
                        
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <h5><i class="fas fa-info-circle me-2"></i>活动信息</h5>
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item d-flex justify-content-between align-items-center bg-transparent">
                                        <span><i class="fas fa-map-marker-alt me-2"></i>活动地点</span>
                                        <span class="text-primary">${activity.location}</span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center bg-transparent">
                                        <span><i class="fas fa-calendar-alt me-2"></i>开始时间</span>
                                        <span class="text-primary">${startTime}</span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center bg-transparent">
                                        <span><i class="fas fa-calendar-check me-2"></i>结束时间</span>
                                        <span class="text-primary">${endTime}</span>
                                    </li>
                                </ul>
                            </div>
                            <div class="col-md-6">
                                <h5><i class="fas fa-user-plus me-2"></i>报名信息</h5>
                                <ul class="list-group list-group-flush">
                                    <li class="list-group-item d-flex justify-content-between align-items-center bg-transparent">
                                        <span><i class="fas fa-clock me-2"></i>报名截止</span>
                                        <span class="text-primary">${deadline}</span>
                                    </li>
                                    <li class="list-group-item d-flex justify-content-between align-items-center bg-transparent">
                                        <span><i class="fas fa-users me-2"></i>参与人数</span>
                                        <span class="text-primary">${activity.currentParticipants}/${activity.maxParticipants || '不限'}</span>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            $('#activityDetailContent').html(content);
            $('#activityDetailModalLabel').text(activity.title);
            
            // 设置报名按钮状态
            const registerBtn = $('#registerActivityBtn');
            
            if (alreadyRegistered) {
                registerBtn.html('<i class="fas fa-check me-2"></i>已报名').addClass('btn-success').removeClass('btn-primary').prop('disabled', true);
            } else if (isFull) {
                registerBtn.html('<i class="fas fa-users-slash me-2"></i>名额已满').addClass('btn-danger').removeClass('btn-primary').prop('disabled', true);
            } else {
                registerBtn.html('<i class="fas fa-user-plus me-2"></i>报名参加').addClass('btn-primary').removeClass('btn-success btn-danger').prop('disabled', false);
            }
        }

        // 报名活动
        function registerForActivity(activityId, userId) {
            console.log('报名活动，活动ID:', activityId, '用户ID:', userId);
            
            if (!activityId || !userId) {
                console.error('活动ID或用户ID为空');
                alert('报名失败：无法获取活动或用户信息');
                return;
            }
            
            // 显示加载状态
            const registerBtn = $('#registerActivityBtn');
            const originalText = registerBtn.html();
            registerBtn.html('<i class="fas fa-spinner fa-spin me-2"></i>报名中...').prop('disabled', true);
            
            $.ajax({
                url: API_BASE_URL + '/activities/' + activityId + '/register/' + userId,
                type: 'POST',
                success: function(response) {
                    console.log('报名请求响应:', response);
                    if (response.code === 200) {
                        // 更新按钮状态
                        registerBtn.html('<i class="fas fa-check me-2"></i>报名成功').addClass('btn-success').removeClass('btn-primary');
                        
                        // 延迟关闭模态框并刷新活动列表
                        setTimeout(function() {
                            $('#activityDetailModal').modal('hide');
                            loadActivities();
                        }, 1500);
                    } else {
                        console.error('报名失败:', response.message);
                        alert('报名失败：' + response.message);
                        registerBtn.html(originalText).prop('disabled', false);
                    }
                },
                error: function(xhr) {
                    console.error('报名请求错误:', xhr);
                    alert('报名失败：' + (xhr.responseJSON?.message || '服务器错误'));
                    registerBtn.html(originalText).prop('disabled', false);
                }
            });
        }
    </script>
</body>
</html> 